using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class PlayerController : MonoBehaviour
{
    
    // [Header("战斗设置")]
    // public float detectionRadius = 5f;// 侦测范围
    // public GameObject bulletPrefab;// 子弹预制体
    // public Transform firePoint;// 子弹发射点
    // public float fireRate = 0.5f;// 子弹发射频率
    // private float nextFireTime = 0f;// 下一次射击时间

    public float speed = 5f;// 角色移动速度

    private Vector3 inputMovement;// 角色输入移动方向向量
    // private Vector3 inputVector = Vector2.zero;// 角色移动方向向量
    
    private Vector3 movement;
    
    // 缓存PlayerSkeletonAnimation的引用
    // private Transform skeletonTransform;// 角色骨骼动画节点
    
    private Vector3 mouseWorldPos; // 鼠标世界坐标位置
    private Vector2 direction; // 方向向量
    
    //动画播放器
    private Animator animator;
    
    public GameObject gunObj;
    private GunScript currentGun;
    
    // 控制模式枚举
    private enum ControlMode
    {
        Mouse,
        Joystick
    }
    
    // 当前控制模式
    private ControlMode currentControlMode = ControlMode.Mouse;
    // 鼠标是否移动的标志
    public bool isMouseMoving = false;
    // 摇杆是否激活的标志
    public bool isJoystickActive = false;
    
    // 缓存Muzzle节点引用
    private Transform muzzleTransform;
    
    // 缓存Gun节点引用
    [SerializeField] private Transform gunTransform;
    
    
    // [Header("状态机相关")]
    // [SerializeField] private Rigidbody2D rb;
    // [SerializeField] private Transform groundCheck;
    // [SerializeField] private LayerMask groundLayer;
    // [SerializeField] private float moveSpeed = 5f;
    // [SerializeField] private float jumpForce = 7f;

    private Vector2 moveInput;
    private bool isJumpPressed;
    private PlayerStateMachine stateMachine;
    // private Vector2 movement;

    private void Awake()
    {
        // if (rb == null)
        //     rb = GetComponent<Rigidbody2D>();

        // 初始化状态机
        stateMachine = GetComponent<PlayerStateMachine>();
        if (stateMachine == null)
            stateMachine = gameObject.AddComponent<PlayerStateMachine>();
    }

    void Start()
    {
        // 初始化PlayerSkeletonAnimation引用
        // skeletonTransform = transform.Find("PlayerSkeletonAnimation");
        // if (skeletonTransform)
        // {
        //     animator = skeletonTransform.GetComponent<Animator>();
        // }
        
        gunObj = transform.Find("Gun").gameObject;
        
        // 默认装备手枪
        // EquipGun("pistol");
    }
    
    void Update()
    {
        // // 检测鼠标移动
        // Vector2 mouseMovement = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
        // isMouseMoving = mouseMovement.magnitude > 0.1f;
        //
        // // 根据当前输入状态决定控制模式
        // if (isMouseMoving && !isJoystickActive)
        // {
        //     currentControlMode = ControlMode.Mouse;
        // }
        // else if (isJoystickActive)
        // {
        //     currentControlMode = ControlMode.Joystick;
        // }
        
        //移动
        

        HandleInput();

        // R键装弹
        if (Input.GetKeyDown(KeyCode.R))
        {
            // currentGun.Reload();
            // GunManager.GetInstance().LoadAllData();
            Debug.Log("枪数量："+GunManager.GetInstance().Getbullets().Count());
            Debug.Log("子弹数量："+GunManager.GetInstance().GetGuns().Count());
        }

        // 数字键切换武器
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            EquipGun("pistol");//手枪
        }
        else if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            EquipGun("shotgun");//霰弹枪
        }
        else if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            EquipGun("rifle");//步枪
        }

        
        
        // var enemiesInRange = activeEnemies
        //     .Where(enemy => Vector2.Distance(transform.position, enemy.transform.position) <= detectionRadius)
        //     .ToList();
        //
        // if (enemiesInRange.Count > 0 && Time.time >= nextFireTime)
        // {
        //     // 使用LINQ找到最近的敌人
        //     GameObject nearestEnemy = enemiesInRange
        //         .OrderBy(enemy => Vector2.Distance(transform.position, enemy.transform.position))
        //         .First();
        //     
        //     Fire(nearestEnemy.transform);
        //     nextFireTime = Time.time + fireRate;
        // }
    }
    
    private void FixedUpdate()
    {
        if (stateMachine != null)
            stateMachine.currentState?.FixedUpdate();
    }

    private void HandleInput()
    {
        movement.x = Input.GetAxisRaw("Horizontal");//GetAxisRaw这个函数不进行平滑处理
        movement.y = Input.GetAxisRaw("Vertical");//GetAxisRaw这个函数不进行平滑处理
        if (movement.x != 0 || movement.y != 0)
        {
            movement = movement.normalized;
            transform.position += movement * Time.deltaTime * speed;
            // FlipWithPlayer();
        }
        else
        {
            //角色移动
            movement = Vector3.ClampMagnitude(inputMovement, speed);
            movement = movement.normalized;
            transform.position += movement * Time.deltaTime * speed;
            // FlipWithPlayer();
        }

        // 跳跃输入
        if (Input.GetButtonDown("Jump"))
        {
            isJumpPressed = true;
        }
    }

    #region 状态机调用方法
    public Vector2 GetMoveInput()
    {
        return movement;
    }

    public bool IsJumpPressed()
    {
        bool result = isJumpPressed;
        isJumpPressed = false; // 重置跳跃输入
        return result;
    }

    // public bool IsGrounded()
    // {
    //     return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    // }

    // public void Move(Vector2 direction)
    // {
        // rb.velocity = new Vector2(direction.x * moveSpeed, rb.velocity.y);
        // FlipWithPlayer();
        
        // HandleInput();
    // }

    // public void StopMovement()
    // {
        // rb.velocity = new Vector2(0, rb.velocity.y);
    // }

    // public void Jump()
    // {
    //     rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    // }
    #endregion

    

    //摇杆控制角色位置
    public void PlayerMove(Vector3 movement)
    {
        inputMovement = movement;
        // Debug.Log("PlayerMove: " + movement);
        
        // 检测是否有有效的摇杆输入
        if (movement.magnitude > 0.1f)
        {
            // 设置摇杆激活标志
            isJoystickActive = true;
            
            // 将方向向量转换为世界坐标中的目标点
            // 计算一个足够远的点，确保子弹有足够的移动空间
            mouseWorldPos = transform.position + movement * 10f;
            
            // 计算角色到目标点的方向矢量
            direction = movement.normalized;
        }
        else
        {
            // 如果摇杆输入很小，可以考虑不更新方向
            // 但保持摇杆激活状态，直到明确的joystickUp事件
        }
    }
    
    public void EquipGun(string gunId)
    {
        // 移除旧枪
        // if (currentGun != null)
        // {
        //     Destroy(currentGun.gameObject);
        // }
        
        // 创建新枪
        // GameObject gunObj = new GameObject("Gun");
        // gunObj.transform.SetParent(gunHolder);
        // gunObj.transform.localPosition = Vector3.zero;
        // gunObj.transform.localRotation = Quaternion.identity;

        currentGun = gunObj.GetComponent<GunScript>();
        if(currentGun == null)
            currentGun = gunObj.AddComponent<GunScript>();
        currentGun.Initialize(gunId);
    }
    
    // 摇杆按下事件
    public void onJoystickDown()
    {
        isJoystickActive = true;
    }
    
    // 摇杆弹起事件
    public void onJoystickUp()
    {
        isJoystickActive = false;
    }

    // 调试绘制范围
    // void OnDrawGizmosSelected()
    // {
    //     Gizmos.color = Color.red;
    //     Gizmos.DrawWireSphere(transform.position, detectionRadius);
    // }
}
